/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.components.pipeline.cards

import cn.nkpro.elcube.annotation.NkNote
import cn.nkpro.elcube.co.spel.NkSpELManager
import cn.nkpro.elcube.docengine.EnumDocClassify
import cn.nkpro.elcube.docengine.NkAbstractCard
import cn.nkpro.elcube.docengine.model.DocDefIV
import cn.nkpro.elcube.docengine.model.DocHV
import cn.nkpro.elcube.exception.NkDefineException
import cn.nkpro.elcube.task.NkBpmDefService
import cn.nkpro.elcube.task.NkDmnService
import cn.nkpro.elcube.task.model.DmnResult
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component

@Order(2002)
@NkNote("执行决策流")
@Component("NkCardPipelineDmn")
class NkCardPipelineDmn extends NkAbstractCard<DmnResult,Def> {

    @Override
    boolean supports(String classify) {
        return true//classify == EnumDocClassify.PIPELINE.name()
    }

    @Autowired
    private NkSpELManager spELManager

    @Autowired
    private NkDmnService dmnService
    @Autowired
    private NkBpmDefService bpmDefService

    @Override
    Object call(DocHV doc, DmnResult data, DocDefIV defIV, Def d, Object options) {

        if(options=='dmn'&&d.key){
            return bpmDefService.getDmnDefinitionByKey(d.key)
        }

        return super.call(doc, data, defIV, d, options)
    }

    @Override
    DmnResult calculate(DocHV doc, DmnResult data, DocDefIV defIV, Def d, boolean isTrigger, Object options) {
        def context = spELManager.createContext(doc)
        if(d.key && d.inputsSpEL){
            def inputs = spELManager.invoke(d.inputsSpEL,context)
            if(!inputs instanceof Map){
                throw new NkDefineException("inputs参数必须返回一个Map")
            }
            return dmnService.exec(d.key, inputs as Map<String, Object>)
        }
        return null
    }


    static class Def implements Serializable{
        String key
        String inputsSpEL
    }
}
